﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using XLETL.Model;
using XLETL.BLL;
using XLETL.ExceptionHandling;
using CodeProject.Dialog;

namespace XLETL.TaskManager.Forms
{
    public partial class BuildTaskDialog : Form
    {
        #region Fields

        TargetDatabase targetDb = null;

        DBInfo dBInfo = null;
        
        TaskInfo currentTaskInfo = new TaskInfo(); // hold the current task info object that keep all changes maden by user 

        List<TargetColumnInfo> workingTrgColumnList = null; // hold the temp list from where items can be removed or added back

        bool isDgvTemplateReady = false; // flag to mark when template designer datagridview is built

        Business.BuildTaskValidator validator = null;

        bool isTaskConfigValid = false;

        #endregion 

        #region Properties
        /// <summary>
        /// Hold the status of save task's operation to report it to the mainform
        /// </summary>
        public bool IsSaveSuccess { get; set; } 
        #endregion

        #region Form methods

        public BuildTaskDialog(DBInfo dInfo) // probably there is a need to pass only dbId, DALClassName, and ConnString
        {
            if (dInfo == null)
            {
                throw new ArgumentNullException("dInfo", "Parameter is null");
            }

            InitializeComponent();            

            // Set title
            this.Text = "Create ETL Task";

            // Save company
            dBInfo = dInfo;

            // Assign CompanyId to the TaskInfo object
            currentTaskInfo.DatabaseID = dInfo.DBId;

            // Display Database name
            tsDatabaseName.Text = dInfo.DBFriendlyName;

            // Assign Database Connection string to TransformationProperty control
            this.transPropTemplate.DatabaseConnString = dInfo.ConnString;
            this.transPropTemplate.PgPluginTarget = Globals.PluginTarget.Source;
          
            this.tpTarget.DatabaseConnString = dInfo.ConnString;
            this.tpTarget.Text = "Target Column Transformation";
            this.tpTarget.PgPluginTarget = Globals.PluginTarget.Target;

            // Instantiate Appropriate TargetDatabase class
            targetDb = new TargetDatabase(dInfo.DALClassName);

            // Instantiate Validator object
            validator = new XLETL.TaskManager.Business.BuildTaskValidator();

            this.DisplayContextHelp();
        }

        private void TaskDialog_Load(object sender, EventArgs e)
        {
            Application.DoEvents();
            // Build the initial Template grid without selection
            BuildTemplateGrid(-1);

            // Bind task details properties
            pgTaskDetails.SelectedObject = currentTaskInfo.TaskDetails;

            // Populate table list from target database  
            Application.DoEvents();
            PopulateComboBoxWithTargetTableList(dBInfo.ConnString, tsCbTableList.ComboBox);

            if (!collapsibleSplitter1.IsCollapsed)
            {
              collapsibleSplitter1.ToggleState();
            }

        }        
        
        private void tsBtnSave_Click(object sender, EventArgs e)
        {
          this.DoValidation(false);

            if (isTaskConfigValid)
            {
                try
                {
                    //currentTaskInfo.PostLoadSQLScriptID = rtbPostLoadScript.Text;
                    currentTaskInfo.PreLoadSQLScriptID = rtbPreLoadScript.Text;
                    currentTaskInfo.TargetTableName = tsCbTableList.Text;                    
                    Task task = new Task();
                    IsSaveSuccess = task.SaveTask(currentTaskInfo);
                    
                    if (IsSaveSuccess)
                    {
                      Directory.CreateDirectory(currentTaskInfo.FileUploadPath);
                      }


                }
                catch (Exception ex)
                {
                    IsSaveSuccess = false;
                    /*if (ExceptionHandleProvider.HandleException(ex, "Global Policy") == true)
                    {
                        throw ex;
                    }*/
                    throw new ApplicationException("Error occured", ex);
                }
                finally
                {
                    this.DialogResult = DialogResult.OK;
                }
            }
        }

        private void tsValidate_Click(object sender, EventArgs e)
        {
          DoValidation(true);
          if (collapsibleSplitter1.IsCollapsed)
          {
            collapsibleSplitter1.ToggleState();            
          }
        }

        private void DoValidation(bool displayConfirmMessage)
        {
          rtbErrors.Clear();
          validator.ClearErrorLog();

          if (currentTaskInfo.TaskDetails.ProcessMode != Globals.LoadMode.InsertAll)
          {
            validator.ValidateKeyFieldsExist(currentTaskInfo.SourceColumns);
          }

          validator.ValidateMandatoryTargetColumns(workingTrgColumnList);
          validator.ValidateUniqueTemplateHeadings(currentTaskInfo.SourceColumns);
          validator.ValidateLookupColumns(currentTaskInfo.SourceColumns);

          // get the validation status
          isTaskConfigValid = validator.IsTaskValid;

          if (!isTaskConfigValid)
          {
            rtbErrors.Text = validator.ErrorLog;
          }
          else if (displayConfirmMessage)
          {
            MsgBox.Show("Task Configuration is valid.", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
          }
        }
        
        #endregion

        #region Template Designer

        private void BuildTemplateGrid(int columnToSelect)
        {
            dgvTemplateDesign.SuspendLayout();

            dgvTemplateDesign.Columns.Clear();
            dgvTemplateDesign.Rows.Clear();

            DataGridViewCheckBoxColumn dgChkBoxColumn;
            DataGridViewTextBoxColumn dgTxtBoxColumn;
            DataGridViewComboBoxColumn dgComboboxColumn;

            DataGridViewTextBoxCell dgvTextboxCell;
            DataGridViewCheckBoxCell dgvCheckboxCell;
            DataGridViewComboBoxCell dgvComboboxCell;

            SourceColumnInfo currentSourceCol = null;

            int i = 0;

            // store the number of source columns
            int counter = currentTaskInfo.SourceColumns.Count;
            int startIndex = 0;

            try
            {
                // generate columns from A to Z
                for (i = 65; i <= 90; i++)
                {
                    if (counter > 0)
                    {
                        currentSourceCol = currentTaskInfo.SourceColumns[startIndex];
                        switch (currentSourceCol.Style)
                        {
                            case Globals.CellStyle.Cell:
                                dgTxtBoxColumn = new DataGridViewTextBoxColumn();
                                dgTxtBoxColumn.HeaderText = currentSourceCol.Name;
                                dgTxtBoxColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
                                dgTxtBoxColumn.ReadOnly = true;
                                dgTxtBoxColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                                dgvTemplateDesign.Columns.Add(dgTxtBoxColumn);
                                break;
                            case Globals.CellStyle.Combobox:
                                dgComboboxColumn = new DataGridViewComboBoxColumn();
                                dgComboboxColumn.HeaderText = currentSourceCol.Name;
                                dgComboboxColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
                                dgComboboxColumn.ReadOnly = true;
                                dgComboboxColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                                dgvTemplateDesign.Columns.Add(dgComboboxColumn);
                                break;
                            case Globals.CellStyle.Checkbox:
                                dgChkBoxColumn = new DataGridViewCheckBoxColumn();
                                dgChkBoxColumn.HeaderText = currentSourceCol.Name;
                                dgChkBoxColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
                                dgChkBoxColumn.ReadOnly = true;
                                dgChkBoxColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                                dgvTemplateDesign.Columns.Add(dgChkBoxColumn);
                                break;
                        }
                        counter--;
                        startIndex++;
                    }
                    else
                    {
                        //dgChkBoxInSource = new DataGridViewCheckBoxColumn();
                        dgTxtBoxColumn = new DataGridViewTextBoxColumn();
                        //dgTxtBoxKeyColumn = new DataGridViewTextBoxColumn();

                        //dgChkBoxInSource.HeaderText = "Map in Template";
                        dgTxtBoxColumn.HeaderText = char.ConvertFromUtf32(i);
                        dgTxtBoxColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
                        dgTxtBoxColumn.ReadOnly = true;
                        dgTxtBoxColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        //dgTxtBoxKeyColumn.HeaderText = "Column Key";

                        //dgvCurrent.Columns.Add(dgTxtBoxKeyColumn);
                        dgvTemplateDesign.Columns.Add(dgTxtBoxColumn);
                        //dgvCurrent.Columns.Add(dgChkBoxInSource);
                    }
                }

                DataGridViewRow dgvRow = null;
                /*foreach (DataGridViewColumn column in dgvTemplateDesign.Columns)
                {
                    switch (column.CellType.Name)
                    {
                        case "DataGridViewTextBoxCell":
                            dgvTextboxCell = new DataGridViewTextBoxCell();
                            dgvRow.Cells.Add(dgvTextboxCell);
                            break;
                        case "DataGridViewComboBoxCell":
                            dgvComboboxCell = new DataGridViewComboBoxCell();
                            dgvRow.Cells.Add(dgvComboboxCell);
                            break;
                    }
                }*/
                
                // now generate several rows
                for (i = 0; i < 10; i++ )
                {
                    dgvRow = new DataGridViewRow();
                        //if (column.CellType is DataGridViewTextBoxCell)
                    //dgvTextboxCell = new DataGridViewTextBoxCell();                   

                    // Add ready cells into row following the correct sequence
                    //dgvRow = new DataGridViewRow();
                    //dgvRow.Cells.Add(dgvKeyCell);
                    //dgvRow.Cells.Add(dgvTextboxCell);
                    //dgvRow.Cells.Add(dgvChkCell);

                    // Add ready row into datagridview
                    dgvTemplateDesign.Rows.Add(dgvRow);
                }

                isDgvTemplateReady = true;

                if (columnToSelect > -1)
                {
                    dgvTemplateDesign.Columns[columnToSelect].Selected = true;
                }
                else
                {
                    dgvTemplateDesign.ClearSelection();
                }

                dgvTemplateDesign.ResumeLayout();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void dgvTemplateDesign_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            // Paint the row number on the row header.
            // The using statement automatically disposes the brush.
            using (SolidBrush b = new SolidBrush(dgvTemplateDesign.RowHeadersDefaultCellStyle.ForeColor))
            {
                e.Graphics.DrawString((e.RowIndex+1).ToString(System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
            }
        }
        
        private void dgvTemplateDesign_SelectionChanged(object sender, EventArgs e)
        {
            if (isDgvTemplateReady)
            {
                if (dgvTemplateDesign.SelectedColumns.Count > 0)
                {
                    int index = dgvTemplateDesign.SelectedCells[0].ColumnIndex;

                    // make sure sourcecolumns exist in the collection
                    if (currentTaskInfo.SourceColumns != null && currentTaskInfo.SourceColumns.Count > index)
                    {
                        pgTemplateColumns.SelectedObject = currentTaskInfo.SourceColumns[index];

                        // bind the transformation control
                        this.transPropTemplate.AllowShowDialog = true;                        
                        this.transPropTemplate.TransList = currentTaskInfo.SourceColumns[index].Transformations;                                                

                                                                    
                        /*MappingInfo mappingInfo = currentTaskInfo.ColumnMapping.Find(delegate(MappingInfo search)
                        {
                            if (search.SourceColumnID.Equals(currentTaskInfo.SourceColumns[index].ID))
                                return true;
                            else
                                return false;
                        });*/

                        // Find Target column's Foreign Table name field that correspond the selected source column 
                        TargetColumnInfo targetColInfo = currentTaskInfo.TargetColumns.Find(delegate(TargetColumnInfo search)
                        {
                            if (search.ID.Equals(currentTaskInfo.SourceColumns[index].TargetColumnID))
                                return true;
                            else
                                return false;
                        });

                        // assign foreign table name, if that exists then it would be used in Lookup transformation 
                        transPropTemplate.DbTableName = targetColInfo.PrimaryToForeignTableName;

                        // show target column details as well
                        pgTargetColumns.SelectedObject = targetColInfo;
                    }
                    else
                    {
                        pgTemplateColumns.SelectedObject = null;
                        this.transPropTemplate.AllowShowDialog = false;
                        this.transPropTemplate.TransList = null;
                    }
                }
                else
                {
                    pgTemplateColumns.SelectedObject = null;
                    this.transPropTemplate.AllowShowDialog = false;
                    this.transPropTemplate.TransList = null;
                }
            }
        }
        
        private void dgvTemplateDesign_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void dgvTemplateDesign_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
            {
                DataGridViewRow recievedData = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
                
                if (recievedData != null)
                {
                    int rowIndex = recievedData.Cells[0].RowIndex;
                    object idValue = recievedData.Cells[0].Value;
                    object nameValue = recievedData.Cells[2].Value;                    

                    SourceColumnInfo sourceColInfo = new SourceColumnInfo()
                    {
                        ID = Guid.NewGuid(),
                        TargetColumnID = (Guid)idValue,
                        Name = (string)nameValue,
                        Style = Globals.CellStyle.Cell, //default style
                        Type = Globals.ColumnType.String //default type
                    };
                    
                    currentTaskInfo.SourceColumns.Add(sourceColInfo);

                    // now rebuild templage designer and select the newly added column which is the last in the sourcecolumn list
                    BuildTemplateGrid(currentTaskInfo.SourceColumns.Count-1);

                    // now remove the column from target list
                    dgvTargetColumnList.Rows.RemoveAt(rowIndex);
                    workingTrgColumnList.RemoveAt(rowIndex);
                }
            }            
        }

        private void dgvTemplateDesign_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo info = dgvTemplateDesign.HitTest(e.X, e.Y);
                if (info.ColumnIndex >= 0)
                {
                    string columnName = dgvTemplateDesign.Columns[info.ColumnIndex].HeaderText;
                    if (columnName != null && columnName.Length > 2)
                        dgvTemplateDesign.DoDragDrop(columnName, DragDropEffects.Copy);
                }
            }
        }

        private void pgTemplateColumns_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            // get index of the selected column
            int selectedTemplateColumn = dgvTemplateDesign.SelectedColumns[0].Index;
            
           //Type gItem = e.ChangedItem.PropertyDescriptor.PropertyType;
            if (e.ChangedItem.PropertyDescriptor.Name.Equals("Name"))
            {
               BuildTemplateGrid(selectedTemplateColumn);                
            }
            else if (e.ChangedItem.PropertyDescriptor.Name.Equals("Style"))
            {
                BuildTemplateGrid(selectedTemplateColumn);
            }
        }
        
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Target Table Data Viewer 
            if (tabControl1.SelectedIndex == 1)
            {
                // Populate it just once
                if (cmbDbTableList.Items.Count == 0)
                {
                    PopulateComboBoxWithTargetTableList(dBInfo.ConnString, cmbDbTableList);
                }
            }
        }
        
        private void dgvTemplateDesign_Enter(object sender, EventArgs e)
        {
            dgvTargetColumnList.ClearSelection();
        }        

        #endregion

        #region Target Data Viewer

        public delegate void TargetTableDataViewAction(object methodParams);        
        
        public void DoTargetTablesDataViewerLoad(object methodParams)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new TargetTableDataViewAction(DoTargetTablesDataViewerLoad), methodParams);
            }
            else
            {
                Cursor.Current = Cursors.WaitCursor;
                object[] mp = (object[])methodParams;
                string conString = Convert.ToString(mp[0]);
                string tableName = Convert.ToString(mp[1]);

                try
                {
                    if (targetDb != null)
                    {
                        DataTable dt = targetDb.GetDataOfTable(conString, tableName, null);
                        if (dt != null)
                        {
                            dgvTargetData.DataSource = dt;
                        }
                    }
                }
                catch (Exception e)
                {                    
                  MessageBox.Show(e.Message);
                }

                Cursor.Current = Cursors.Default;
            }
        }         

        /// <summary>
        /// Table Data Viewer's table list select event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbDbTableList_SelectedIndexChanged(object sender, EventArgs e)
        {
          if (cmbDbTableList.SelectedIndex > 0)
          {
            object[] methodParams = new object[] { dBInfo.ConnString, cmbDbTableList.Text };
            if (ThreadPool.QueueUserWorkItem(new WaitCallback(DoTargetTablesDataViewerLoad), methodParams))
            {
              //SetSatusText("Loading " + plugin.Name + " ...", StatusMessageType.Busy);
            }
            else
            {
              DoTargetTablesDataViewerLoad(methodParams);
            }
          }
        }

        #endregion

        #region Target Columns

        //public delegate void TargetTableColumnAction(object connString);

        private void DisplayTableColumns(DataGridView dgvCurrent, List<TargetColumnInfo> columnCol)
        {
            dgvCurrent.Columns.Clear();
            dgvCurrent.Rows.Clear();

            DataGridViewTextBoxColumn dgTxtBoxIDColumn;
            DataGridViewTextBoxColumn dgTxtBoxColumn;
            DataGridViewTextBoxColumn dgTxtBoxKeyColumn;

            try
            {
                dgTxtBoxIDColumn = new DataGridViewTextBoxColumn();
                dgTxtBoxColumn = new DataGridViewTextBoxColumn();
                dgTxtBoxKeyColumn = new DataGridViewTextBoxColumn();

                dgTxtBoxColumn.HeaderText = "Column Name";
                dgTxtBoxColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgTxtBoxKeyColumn.HeaderText = "Key";
                dgTxtBoxKeyColumn.Width = 30;
                dgTxtBoxIDColumn.Visible = false;

                dgvCurrent.Columns.Add(dgTxtBoxIDColumn);
                dgvCurrent.Columns.Add(dgTxtBoxKeyColumn);
                dgvCurrent.Columns.Add(dgTxtBoxColumn);
                                

                foreach (TargetColumnInfo row in columnCol)
                {
                    string keyValue = "";
                    DataGridViewTextBoxCell dgvKeyCell = new DataGridViewTextBoxCell();
                    if (row.IsPrimaryKey)
                    {
                        keyValue += "PK";
                    }
                    if (row.IsForeignKey)
                    {
                        if (keyValue.Length > 0)
                        {
                            keyValue += ",";
                        }
                        keyValue += "FK";
                    }

                    dgvKeyCell.Value = keyValue;

                    DataGridViewTextBoxCell dgvTextboxCell = new DataGridViewTextBoxCell();
                    dgvTextboxCell.Value = row.Name;

                    DataGridViewTextBoxCell dgvIDCell = new DataGridViewTextBoxCell();
                    dgvIDCell.Value = row.ID;

                    // Add ready cells into row following the correct sequence
                    DataGridViewRow dgvRow = new DataGridViewRow();
                    if (!row.IsDefaultNull)
                    {
                        dgvRow.DefaultCellStyle.ForeColor = Color.Red;
                    }
                    else
                    {
                        dgvRow.DefaultCellStyle.ForeColor = Color.Black;
                    }
                    dgvRow.Cells.Add(dgvIDCell);
                    dgvRow.Cells.Add(dgvKeyCell);
                    dgvRow.Cells.Add(dgvTextboxCell);                    

                    // Add ready row into datagridview
                    dgvCurrent.Rows.Add(dgvRow);
                }

                dgvCurrent.ClearSelection();

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void PopulateComboBoxWithTargetTableList(string connString, ComboBox cmbControl)
        {
            if (targetDb != null)
            {
                DataTable dtTblList = targetDb.GetDatabaseTableList(connString);

                DataRow dr = dtTblList.NewRow();
                dr["TABLE_NAME"] = "-- Select Table --";
                dtTblList.Rows.InsertAt(dr, 0);

                cmbControl.DisplayMember = "TABLE_NAME";
                cmbControl.ValueMember = "TABLE_NAME";
                cmbControl.DataSource = dtTblList;
            }
        }       

        private void dgvTargetColumnList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvTargetColumnList.SelectedCells.Count > 0)
            {
                int index = dgvTargetColumnList.SelectedCells[0].RowIndex;
                if (index >= 0)
                {
                    object idValue = dgvTargetColumnList.Rows[index].Cells[0].Value;

                    TargetColumnInfo columnInfo = currentTaskInfo.TargetColumns.Find(delegate(TargetColumnInfo search)
                    {
                        if (search.ID.Equals(idValue))
                            return true;
                        else
                            return false;
                    });

                    pgTargetColumns.SelectedObject = columnInfo;
                    tpTarget.AllowShowDialog = true;
                    tpTarget.TransList = columnInfo.Transformations;

                    // Save Previous Column's Settings

                    //currentTaskInfo.SourceColumns
                }
            }
            else
            {
                tpTarget.AllowShowDialog = false;
                tpTarget.TransList = null;
                pgTargetColumns.SelectedObject = null;
            }
        }        

        private void dgvTargetColumnList_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo info = dgvTargetColumnList.HitTest(e.X, e.Y);
                if (info.RowIndex >= 0)
                {
                    DataGridViewRow rowView = dgvTargetColumnList.Rows[info.RowIndex];
                    if (rowView != null)
                        dgvTargetColumnList.DoDragDrop(rowView, DragDropEffects.Copy);
                }
            }

        }

        private void dgvTargetColumnList_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(string)))
            {
                string recievedData = (string)e.Data.GetData(typeof(string));

                if (recievedData != null)
                {
                    // Now find the source column equal to the recieved name
                    SourceColumnInfo sourceColInfo = currentTaskInfo.SourceColumns.Find(delegate(SourceColumnInfo search)
                    {
                        if (search.Name.Equals(recievedData))
                            return true;
                        else
                            return false;
                    });

                    // Now remove the found column from the SourceColumn and ColumnMapping lists
                    if (sourceColInfo != null)
                    {
                        // Now find the mapping column based on the found column id
                        //MappingInfo mappingInfo = currentTaskInfo.ColumnMapping.Find(delegate(MappingInfo search)
                        //{
                        //    if (search.SourceColumnID.Equals(sourceColInfo.ID))
                        //        return true;
                        //    else
                        //        return false;
                        //});

                        TargetColumnInfo targetColInfo = currentTaskInfo.TargetColumns.Find(delegate(TargetColumnInfo search)
                        {
                            if (search.ID.Equals(sourceColInfo.TargetColumnID))
                                return true;
                            else
                                return false;
                        });

                        currentTaskInfo.SourceColumns.Remove(sourceColInfo);
                        //currentTaskInfo.ColumnMapping.Remove(mappingInfo);

                        // put that column back
                        // TODO: return the column on the same place but take into account that the orderIndex 
                        //       can be changed as the other columns might be dragged out already.
                        //workingTrgColumnList.Insert(targetColInfo.OrderIndex, targetColInfo);
                        workingTrgColumnList.Add(targetColInfo);

                        // now rebuild templage designer and clear selection
                        BuildTemplateGrid(-1);

                        // now rebuild target column datagridview
                        DisplayTableColumns(this.dgvTargetColumnList, workingTrgColumnList);
                    }
                }
            }
        }

        private void dgvTargetColumnList_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void tsCbTableList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //TODO: make check if any data exist for the previous table and warn user the data will be lost

            /*object[] methodParams = new object[] { dBInfo.ConnString, tsCbTableList.Text };
            if (ThreadPool.QueueUserWorkItem(new WaitCallback(DoTargetTableColumnsLoad), methodParams))
            {
                //SetSatusText("Loading " + plugin.Name + " ...", StatusMessageType.Busy);
            }
            else
            {
                DoTargetTableColumnsLoad(methodParams);
            }*/
            Application.DoEvents();
            Cursor.Current = Cursors.WaitCursor;
            Application.DoEvents();

            // ignore the "Select Table" item
            if (tsCbTableList.SelectedIndex > 0)
            {
              // set default Task name based on the selected target table
              currentTaskInfo.TaskDetails.Name = string.Format("New {0} data", tsCbTableList.Text);
              currentTaskInfo.TaskDetails.SourceSheetName = tsCbTableList.Text;              
            }
            else
            {
              currentTaskInfo.TaskDetails.Name = "";
              currentTaskInfo.TaskDetails.SourceSheetName = "";              
            }

            pgTaskDetails.Refresh();
            workingTrgColumnList = targetDb.GetTargetColumnListByTableName(dBInfo.ConnString, tsCbTableList.Text);
            
            // display column properties
            if (workingTrgColumnList != null)
            {
                currentTaskInfo.TargetColumns = new List<TargetColumnInfo>(workingTrgColumnList);

                DisplayTableColumns(this.dgvTargetColumnList, workingTrgColumnList);
            }

            Application.DoEvents();
            Cursor.Current = Cursors.Default;
            Application.DoEvents();
        }

        private void dgvTargetColumnList_Enter(object sender, EventArgs e)
        {
            dgvTemplateDesign.ClearSelection();
        }
        
        #endregion        

        #region Transformation

        private void transPropTemplate_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            int index = dgvTemplateDesign.SelectedCells[0].ColumnIndex;

            if (currentTaskInfo.SourceColumns != null && currentTaskInfo.SourceColumns.Count > index)
            {
                currentTaskInfo.SourceColumns[index].Transformations = transPropTemplate.TransList;
            }
        }

        private void tpTarget_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            int index = dgvTargetColumnList.SelectedCells[0].RowIndex;
            if (index >= 0)
            {

            }
        }
        
        #endregion

        private void DisplayContextHelp()
        {
          //StringBuilder sbHelp = new StringBuilder();
          //sbHelp.Append("Defining ETL Task configurations");
          rtbHelp.Multiline = true;
          rtbHelp.WordWrap = false;
          rtbHelp.AcceptsTab = true;
          rtbHelp.ScrollBars = RichTextBoxScrollBars.ForcedBoth;

          rtbHelp.SelectionColor = Color.Blue;
          rtbHelp.SelectionFont = new Font("Courier New", 9, FontStyle.Bold);
          rtbHelp.SelectedText = "Building ETL Task configuration:\r\n";
          rtbHelp.SelectionColor = Color.Black;
          //rtbHelp.SelectionFont = new Font("Courier New", 8, FontStyle.Underline);
          //rtbHelp.SelectedText = "- Set Task Details:\n";
          rtbHelp.SelectionFont = new Font("Courier New", 9, FontStyle.Regular);
          
          rtbHelp.SelectedText = " 1.Select Target Table from the list of available Target Database Tables\n";
          rtbHelp.SelectedText = "  2. Set the Task Name, Description, Process Mode\n";
          rtbHelp.SelectedText = "  3. Create Template Columns: Drag and drop desired target columns from Target Column Data grid into Template Designer using right mouse button\n";
          rtbHelp.SelectedText = "  4. Set Template Fields Properties: Column Heading, Column Type, Column Style, Key Field, Number Formating\n";
          rtbHelp.SelectedText = "  5. Define Template Column Transformations\n";
          rtbHelp.SelectedText = "  6. Define Target Table Column Transformations\n";
          rtbHelp.SelectedText = "  7. Create Pre / Post Load Process SQL Scripts\n";
          rtbHelp.SelectedText = "  8. Validate Task Configuration by clicking the Validate button\n";
          rtbHelp.SelectedText = "  9. Save created task configuration by clicking the Save button\n";
          

        }        


        

        

        

        

        

        

        

        
        

              
    }
}
